package com.openx.cloud.server.autoconfigure.security.oauth2;

import org.springframework.security.authentication.*;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.*;
import org.springframework.security.oauth2.provider.token.AbstractTokenGranter;
import org.springframework.util.StringUtils;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 自定义GrantType认证
 *
 * @author yadu
 */
public class CustomTokenGranter extends AbstractTokenGranter {

    private String principalKey;

    private String credentialsKey;

    private AuthenticationManager authenticationManager;

    private List<UserTokenAuthenticationHandler> handlers;


    public CustomTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerEndpointsConfigurer endpointsConfigurer, String grantType, String principalKey, String credentialsKey, List<UserTokenAuthenticationHandler> handlers) {
        super(endpointsConfigurer.getTokenServices(), endpointsConfigurer.getClientDetailsService(), endpointsConfigurer.getOAuth2RequestFactory(), grantType);
        this.principalKey = principalKey;
        this.credentialsKey = credentialsKey;
        this.authenticationManager = authenticationManager;
        this.handlers = handlers;
    }


    @Override
    protected OAuth2Authentication getOAuth2Authentication(ClientDetails client, TokenRequest tokenRequest) {

        Map<String, String> parameters = new LinkedHashMap<String, String>(tokenRequest.getRequestParameters());
        // 用户标示
        String principal = parameters.get(principalKey);
        // 用户凭证
        String credentials = parameters.get(credentialsKey);
        if (StringUtils.isEmpty(principal)) {
            throw new InvalidGrantException("缺少参数:" + principalKey);
        }

        if (StringUtils.isEmpty(credentials)) {
            throw new InvalidGrantException("缺少参数:" + credentials);
        }
        Authentication userAuth = new UsernamePasswordAuthenticationToken(principal, credentials);
        ((AbstractAuthenticationToken) userAuth).setDetails(parameters);
        try {
            userAuth = authenticationManager.authenticate(userAuth);
        } catch (AccountStatusException ase) {
            //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31)
            throw new InvalidGrantException(ase.getMessage());
        } catch (BadCredentialsException e) {
            // If the username/password are wrong the spec says we should send 400/invalid grant
            throw new InvalidGrantException(e.getMessage());
        }
        if (userAuth == null || !userAuth.isAuthenticated()) {
            throw new InvalidGrantException("Could not authenticate user: " + principal);
        }
        // 认证成功调用
        this.success(tokenRequest, userAuth);
        OAuth2Request storedOAuth2Request = getRequestFactory().createOAuth2Request(client, tokenRequest);
        return new OAuth2Authentication(storedOAuth2Request, userAuth);
    }

    /**
     * 前置认证处理
     */
    private void success(TokenRequest tokenRequest, Authentication authentication) {
        if (this.handlers != null) {
            for (UserTokenAuthenticationHandler exchanger : handlers) {
                if (exchanger.support(tokenRequest)) {
                    exchanger.success(tokenRequest, authentication);
                    return;
                }
            }
        }
    }

}
